const messagesArea = document.getElementById('messagesArea');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const typingIndicator = document.getElementById('typingIndicator');

let messageHistory = [];
let isResizing = false;
let startX = 0;
let startWidth = 0;
let currentConversationId = null;
let conversations = [];
let isHistorySidebarOpen = true;

// 自动调整输入框高度
messageInput.addEventListener('input', function () {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 150) + 'px';
});

let first_message = null

// 发送消息
async function sendMessage() {
    const message = messageInput.value.trim();
    if (!message) return;
    first_message = message
    const welcomeMessage = document.querySelector('.welcome-message');
    if (welcomeMessage) {
        welcomeMessage.style.display = 'none';
    }

    addMessage(message, 'user');
    messageInput.value = '';
    messageInput.style.height = 'auto';
    showTypingIndicator();

    // 构造 messages 数组（适配后端结构）
    const messages = messageHistory.map(m => ({
        role: m.type === 'user' ? 'user' : 'assistant',
        content: m.content
    }));


    try {
        const response = await fetch("/api/chat/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                'X-CSRFToken': getCookie('csrftoken'),
            },
            body: JSON.stringify({messages: messages, conversation_id: currentConversationId})
        });

        // 隐藏打字指示器，准备流式显示
        hideTypingIndicator();

        // 创建一个空的助手消息容器用于流式更新
        const assistantMessageDiv = createStreamingMessage();

        // 处理流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let assistantContent = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const jsonStr = line.substring(6);
                    if (jsonStr.trim()) {
                        try {
                            const data = JSON.parse(jsonStr);

                            // 处理流式内容
                            if (data.content) {
                                assistantContent += data.content;
                                updateStreamingMessage(assistantMessageDiv, assistantContent);
                            }

                            // 处理最终完成信息
                            if (data.done) {
                                // 更新历史对话列表
                                loadConversationHistory();

                                // 显示问卷推荐（如果有）
                                if (data.type_int === 0 && data.questionnaire_list) {
                                    showQuestionnaireList(data.questionnaire_list);
                                }

                                // 添加额外消息（如果有）
                                if (data.extra_message) {
                                    assistantContent += data.extra_message;
                                    updateStreamingMessage(assistantMessageDiv, assistantContent);
                                }
                            }
                        } catch (e) {
                            console.error('Error parsing JSON:', e);
                        }
                    }
                }
            }
        }

        // 保存最终的助手回复到历史记录
        messageHistory.push({
            content: assistantContent,
            type: 'assistant',
            timestamp: new Date()
        });

    } catch (error) {
        hideTypingIndicator();
        addMessage("出错了，请稍后再试。", 'assistant');
        console.error("Error:", error);
    }
}

// 创建用于流式更新的消息容器
function createStreamingMessage() {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message assistant';

    const avatar = document.createElement('div');
    avatar.className = 'message-avatar assistant-avatar';
    avatar.textContent = '🤖';

    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.innerHTML = ''; // 开始时为空

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentDiv);
    messagesArea.appendChild(messageDiv);

    // 滚动到底部
    messagesArea.scrollTop = messagesArea.scrollHeight;

    return messageDiv;
}

// 更新流式消息内容
function updateStreamingMessage(messageDiv, content) {
    const contentDiv = messageDiv.querySelector('.message-content');

    // 使用 marked.js 解析 Markdown 并设置 HTML 内容
    const markdownHtml = marked.parse(content);
    contentDiv.innerHTML = markdownHtml;

    // 滚动到底部
    messagesArea.scrollTop = messagesArea.scrollHeight;
}

// 显示问卷函数
function showQuestionnaireList(list) {
    const container = document.getElementById('questionnaireContainer');
    const listDiv = document.getElementById('questionnaireList');
    const embedArea = document.getElementById('questionnaireEmbedArea'); // 新增容器用于嵌入问卷脚本


    container.style.display = 'block';
    listDiv.innerHTML = ''; // 清空旧列表
    embedArea.innerHTML = ''; // 清空嵌入区域
    let i = 1
    list.forEach(q => {
        const item = document.createElement('div');
        item.className = 'questionnaire-item';
        item.style.marginBottom = '10px';

        const h2 = document.createElement('h2');
        h2.textContent = "推荐问卷" + i;
        i = i + 1
        // 创建 button，并用 flex 布局包装图标 + 文字
        const button = document.createElement('button');
        button.style.display = 'flex';               // 横向排列图标和文字
        button.style.alignItems = 'center';          // 垂直居中
        button.style.gap = '8px';                    // 图标和文字间距
        button.style.color = '#3b82f6';
        button.style.textDecoration = 'none';
        button.style.padding = '12px 20px';
        button.style.fontSize = '16px';
        button.style.border = '2px solid #3b82f6';
        button.style.backgroundColor = '#e0f2fe';
        button.style.borderRadius = '8px';
        button.style.cursor = 'pointer';

        // 创建图标
        const icon = document.createElement('span');
        icon.textContent = '📄'; // 或者用 SVG、图片等
        icon.style.fontSize = '18px';

        // 创建文字节点
        const text = document.createElement('span');
        text.textContent = q.title_page || '未命名问卷';

        // 按顺序添加到按钮中
        button.appendChild(icon);
        button.appendChild(text);

        item.appendChild(h2);
        item.appendChild(button);
        listDiv.appendChild(item);

        // 添加点击事件
        button.addEventListener('click', () => {
            embedArea.innerHTML = '';
            window.question_name = q.title_page;
            window.question_id = q.id_page;
            const iframe = document.createElement('iframe');
            iframe.type = 'text/javascript';
            iframe.style.width = '100%';
            iframe.style.height = '500px';
            iframe.style.border = 'none';
            iframe.src = "/questions";
            // 监听 iframe 加载完毕后传递数据
            iframe.onload = () => {
                iframe.contentWindow.postMessage(
                    {
                        question_name: window.question_name,
                        question_id: window.question_id,
                    },
                    '*'
                );
            };
            embedArea.appendChild(iframe);
        });
    });
}

/**
 * 历史对话部分
 */

// 切换历史对话侧边栏
function toggleHistorySidebar() {
    const sidebar = document.getElementById('historySidebar');
    const toggleBtn = sidebar.querySelector('.history-toggle svg path');

    sidebar.classList.toggle('collapsed');

    // 更新箭头方向
    if (sidebar.classList.contains('collapsed')) {
        toggleBtn.setAttribute('d', 'M9 18L15 12L9 6');
    } else {
        toggleBtn.setAttribute('d', 'M15 18L9 12L15 6');
    }
}

// 初始化缩放手柄
function initializeResizeHandle() {
    const resizeHandle = document.getElementById('resizeHandle');
    const historySidebar = document.getElementById('historySidebar');

    if (!resizeHandle || !historySidebar) return;

    resizeHandle.addEventListener('mousedown', function(e) {
        isResizing = true;
        startX = e.clientX;
        startWidth = parseInt(document.defaultView.getComputedStyle(historySidebar).width, 10);

        resizeHandle.classList.add('dragging');
        document.body.style.cursor = 'col-resize';
        document.body.style.userSelect = 'none';

        e.preventDefault();
    });

    document.addEventListener('mousemove', function(e) {
        if (!isResizing) return;

        const width = startWidth + e.clientX - startX;
        const minWidth = 200;
        const maxWidth = 500;

        if (width >= minWidth && width <= maxWidth) {
            historySidebar.style.width = width + 'px';
        }
    });

    document.addEventListener('mouseup', function() {
        if (isResizing) {
            isResizing = false;
            resizeHandle.classList.remove('dragging');
            document.body.style.cursor = 'default';
            document.body.style.userSelect = 'auto';
        }
    });
}

// 页面加载完成后初始化历史对话
document.addEventListener('DOMContentLoaded', function() {
    initializeHistoryChat();
    setupHistoryEventListeners();
});

// 初始化历史对话功能
function initializeHistoryChat() {
    loadConversationHistory();
    setupResizeHandle();
}

// 设置历史对话相关的事件监听器
function setupHistoryEventListeners() {
    // 监听新消息发送，更新历史记录
    const sendButton = document.getElementById('sendButton');
    const messageInput = document.getElementById('messageInput');

    if (sendButton) {
        sendButton.addEventListener('click', function() {
            handleNewMessage();
        });
    }

    if (messageInput) {
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleNewMessage();
            }
        });
    }
}

// 加载历史对话列表
async function loadConversationHistory() {
    try {
        const response = await fetch('/api/history_list/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
            }
        });

        if (response.ok) {
            const data = await response.json();
            conversations = data.conversations || [];
            displayConversationHistory();
        } else {
            console.error('无法加载对话历史记录');
            showDefaultConversations();
        }
    } catch (error) {
        console.error('加载对话历史记录时出错：', error);
        showDefaultConversations();
    }
}

// 设置侧边栏大小调整功能
function setupResizeHandle() {
    const resizeHandle = document.getElementById('resizeHandle');
    const sidebar = document.getElementById('historySidebar');

    if (!resizeHandle || !sidebar) return;

    let isResizing = false;

    resizeHandle.addEventListener('mousedown', (e) => {
        isResizing = true;
        document.addEventListener('mousemove', handleResize);
        document.addEventListener('mouseup', stopResize);
    });

    function handleResize(e) {
        if (!isResizing) return;

        const newWidth = e.clientX;
        if (newWidth >= 200 && newWidth <= 400) {
            sidebar.style.width = newWidth + 'px';
        }
    }

    function stopResize() {
        isResizing = false;
        document.removeEventListener('mousemove', handleResize);
        document.removeEventListener('mouseup', stopResize);
    }
}

// 显示历史对话列表
function displayConversationHistory() {
    const conversationList = document.getElementById('conversationList');
    if (!conversationList) return;

    // 清空现有内容
    conversationList.innerHTML = '';

    if (conversations.length === 0) {
        conversationList.innerHTML = `
            <div class="conversation-preview active">
                <div style="font-weight: 600;color: #2d3748;margin-bottom: 5px;font-size: 14px;display: flex;align-items: center;">暂无历史对话</div>
                <div class="conversation-last">开始您的第一次对话吧！</div>
            </div>
        `;
        return;
    }

    // 渲染每个对话
    conversations.forEach(conversation => {
        const conversationElement = createConversationElement(conversation);
        conversationList.appendChild(conversationElement);
    });
}

// 创建单个对话元素
function createConversationElement(conversation) {
    const div = document.createElement('div');
    div.className = `conversation-preview ${conversation.id === currentConversationId ? 'active' : ''}`;
    div.dataset.conversationId = conversation.id;

    // 格式化时间
    const timeString = formatTime(conversation.updated_at || conversation.created_at);

    // 截取最后一条消息用于预览
    const lastMessage = conversation.last_message || '开始对话...';
    const truncatedMessage = lastMessage.length > 30 ? lastMessage.substring(0, 30) + '...' : lastMessage;

    div.innerHTML = `
        <div class="conversation-content" onclick="loadConversation(${conversation.id})">
            <div class="conversation-title">${escapeHtml(conversation.title || '新对话')}</div>
            <div class="conversation-last">${escapeHtml(truncatedMessage)}</div>
            <div class="conversation-time">${timeString}</div>
        </div>
        <div class="conversation-actions">
            <button class="action-btn delete-btn" onclick="deleteConversation(${conversation.id})" title="删除对话">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        </div>
    `;

    return div;
}

// 删除对话
async function deleteConversation(conversationId) {
    if (!confirm('确定要删除这个对话吗？此操作不可恢复。')) {
        return;
    }
    const authToken = sessionStorage.getItem('auth_token');
    try {
        const response = await fetch(`/api/history_del/${conversationId}/`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
                'Authorization': `Bearer ${authToken}`,
            },
            credentials: 'include'
        });

        if (response.ok) {
            // 如果删除的是当前对话，清空聊天区域
            if (conversationId === currentConversationId) {
                currentConversationId = null;
                clearChatArea();
                showWelcomeMessage();
            }

            // 重新加载历史对话列表
            await loadConversationHistory();

            showSuccessMessage('对话已删除');
        } else {
            console.error('Failed to delete conversation');
            showErrorMessage('删除对话失败，请重试');
        }
    } catch (error) {
        console.error('Error deleting conversation:', error);
        showErrorMessage('删除对话时发生错误');
    }
}

// 显示错误消息
function showErrorMessage(message) {
    // 这里可以集成您的消息提示组件
    console.error(message);
    alert(message);
}

// 显示欢迎消息
function showWelcomeMessage() {
    const welcomeMessage = document.querySelector('.welcome-message');
    if (welcomeMessage) {
        welcomeMessage.style.display = 'flex';
    }
}

// 显示成功消息
function showSuccessMessage(message) {
    // 这里可以集成您的消息提示组件
    console.log(message);
}

// 加载特定对话
async function loadConversation(conversationId) {
    const authToken = sessionStorage.getItem('auth_token');
    try {
        // 显示加载状态
        showTypingIndicator();

        const response = await fetch(`/api/conversations/${conversationId}/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
                'Authorization': `Bearer ${authToken}`,
            },
            credentials: 'include'
        });

        if (response.ok) {
            const data = await response.json();
            currentConversationId = conversationId;

            // 更新UI中的活跃对话
            updateActiveConversation(conversationId);

            // 加载消息到聊天区域
            loadMessagesToChat(data.messages || []);

            // 隐藏欢迎消息
            const welcomeMessage = document.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.style.display = 'none';
            }

            // 启用输入框，允许继续对话
            enableChatInput();

            // 显示对话信息
            showConversationInfo(data);

        } else {
            console.error('Failed to load conversation');
            showErrorMessage('加载对话失败，请重试');
        }
    } catch (error) {
        console.error('Error loading conversation:', error);
        showErrorMessage('加载对话时发生错误');
    } finally {
        hideTypingIndicator();
    }
}

// 显示对话信息
function showConversationInfo(conversationData) {
    const messagesArea = document.getElementById('messagesArea');
    if (!messagesArea) return;

    // 创建对话信息头部
    const existingInfo = messagesArea.querySelector('.conversation-info');
    if (existingInfo) {
        existingInfo.remove();
    }

    const infoElement = document.createElement('div');
    infoElement.className = 'conversation-info';
    infoElement.innerHTML = `
        <div class="conversation-header">
            <h3>${escapeHtml(conversationData.title || '对话')}</h3>
            <div class="conversation-meta">
                <span>创建于: ${formatTime(conversationData.created_at)}</span>
                <span>最后更新: ${formatTime(conversationData.updated_at)}</span>
            </div>
        </div>
        <div class="conversation-divider"></div>
    `;

    // 插入到消息区域顶部
    messagesArea.insertBefore(infoElement, messagesArea.firstChild);
}

// 更新活跃对话状态
function updateActiveConversation(conversationId) {
    // 移除所有活跃状态
    const allConversations = document.querySelectorAll('.conversation-preview');
    allConversations.forEach(conv => conv.classList.remove('active'));

    // 为当前对话添加活跃状态
    const currentConv = document.querySelector(`[data-conversation-id="${conversationId}"]`);
    if (currentConv) {
        currentConv.classList.add('active');
    }
}

// 将消息加载到聊天区域
function loadMessagesToChat(messages) {
    const messagesArea = document.getElementById('messagesArea');
    if (!messagesArea) return;

    // 清空现有消息（保留欢迎消息）
    const existingMessages = messagesArea.querySelectorAll('.message:not(.welcome-message)');
    existingMessages.forEach(msg => msg.remove());

    // 添加历史消息
    messages.forEach((message, index) => {
        const messageElement = createMessageElement(message, index);
        messagesArea.appendChild(messageElement);

        // 添加动画效果
        setTimeout(() => {
            messageElement.style.opacity = '1';
            messageElement.style.transform = 'translateY(0)';
        }, index * 100);
    });

    // 滚动到底部
    setTimeout(() => {
        scrollToBottom();
    }, messages.length * 100 + 200);
}

// 创建消息元素
function createMessageElement(message, index = 0) {
    const div = document.createElement('div');
    div.className = `message ${message.role === 'user' ? 'user-message' : 'assistant-message'}`;
    div.style.opacity = '0';
    div.style.transform = 'translateY(20px)';
    div.style.transition = 'opacity 0.3s ease, transform 0.3s ease';

    // 添加消息时间戳
    const timestamp = formatTime(message.created_at || message.timestamp);

    if (message.role === 'user') {

        div.innerHTML = `
            <div class="message-avatar user-avatar">🤖</div>
            <div class="message-content">
                <div class="message-text">${formatMessageContent(message.content)}</div>
                <div class="message-time">${timestamp}</div>
                
            </div>
        `;
    } else {
        div.innerHTML = `
            <div class="message-avatar assistant-avatar">AI</div>
            <div class="message-content">
                <div class="message-text">${formatMessageContent(message.content)}</div>
                <div class="message-time">${timestamp}</div>
                <div class="message-actions">
                    <div class="button-item">
                        <button class="glass-copy-btn" onclick="copyMessage(this)" title="复制消息">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                                <rect x="9" y="9" width="13" height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2" fill="none"/>
                                <path d="M5 15H4C3.46957 15 2.96086 14.7893 2.58579 14.4142C2.21071 14.0391 2 13.5304 2 13V4C2 3.46957 2.21071 2.96086 2.58579 2.58579C2.96086 2.21071 3.46957 2 4 2H13C13.5304 2 14.0391 2.21071 14.4142 2.58579C14.7893 2.96086 15 3.46957 15 4V5" stroke="currentColor" stroke-width="2" fill="none"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    return div;
}

// 显示默认对话（用于API失败时的后备方案）
function showDefaultConversations() {
    const conversationList = document.getElementById('conversationList');
    if (!conversationList) return;

    conversationList.innerHTML = `
        <div class="conversation-preview active" onclick="loadConversation(1)">
            <div class="conversation-title">考试焦虑咨询</div>
            <div class="conversation-last">我总是觉得很紧张怎么办？最近考试压力特别大...</div>
            <div class="conversation-time">2小时前</div>
        </div>
        <div class="conversation-preview" onclick="loadConversation(2)">
            <div class="conversation-title">情绪管理问题</div>
            <div class="conversation-last">最近情绪波动很大，不知道怎么控制自己的情绪</div>
            <div class="conversation-time">昨天</div>
        </div>
        <div class="conversation-preview" onclick="loadConversation(3)">
            <div class="conversation-title">人际关系困扰</div>
            <div class="conversation-last">和同学相处总是有问题，感觉很孤独</div>
            <div class="conversation-time">3天前</div>
        </div>
        <div class="conversation-preview" onclick="loadConversation(4)">
            <div class="conversation-title">学习压力</div>
            <div class="conversation-last">学习任务太重，感觉快要崩溃了</div>
            <div class="conversation-time">1周前</div>
        </div>
    `;
}

/**
 * 历史对话部分
 */

// HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 格式化消息内容（支持Markdown）
function formatMessageContent(content) {
    if (typeof marked !== 'undefined') {
        return marked.parse(content);
    }
    return escapeHtml(content);
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;

    if (diff < 60000) { // 1分钟内
        return '刚刚';
    } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前';
    } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前';
    } else if (diff < 604800000) { // 1周内
        return Math.floor(diff / 86400000) + '天前';
    } else {
        return date.toLocaleDateString();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeResizeHandle();
});

// 清空聊天区域
function clearChatArea() {
    const messagesArea = document.getElementById('messagesArea');
    if (messagesArea) {
        const messages = messagesArea.querySelectorAll('.message:not(.welcome-message)');
        messages.forEach(msg => msg.remove());
    }
}

// 关闭iframe的函数
function closeIframe() {
    const iframeWrapper = document.getElementById('questionnaireIframeWrapper');
    const iframe = document.getElementById('questionnaireIframe');
    iframeWrapper.style.display = 'none';
    iframe.src = '';
}

// 添加消息到聊天区域
function addMessage(content, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;

    const avatar = document.createElement('div');
    avatar.className = `message-avatar ${type}-avatar`;
    avatar.textContent = type === 'user' ? '您' : '🤖';

    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';

    // 使用 marked.js 解析 Markdown 并设置 HTML 内容
    const markdownHtml = marked.parse(content);
    contentDiv.innerHTML = markdownHtml;

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentDiv);
    messagesArea.appendChild(messageDiv);

    // 滚动到底部
    messagesArea.scrollTop = messagesArea.scrollHeight;

    // 保存到历史记录
    messageHistory.push({content, type, timestamp: new Date()});
}

// 显示打字指示器
function showTypingIndicator() {
    typingIndicator.style.display = 'block';
    messagesArea.scrollTop = messagesArea.scrollHeight;
}

// 隐藏打字指示器
function hideTypingIndicator() {
    typingIndicator.style.display = 'none';
}

// 发送按钮点击事件
sendButton.addEventListener('click', sendMessage);

// 回车发送消息
messageInput.addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

// 输入框焦点管理
messageInput.addEventListener('focus', function () {
    this.style.borderColor = '#3b82f6';
});

messageInput.addEventListener('blur', function () {
    this.style.borderColor = '#d1d5db';
});

// 初始化时聚焦输入框
window.addEventListener('load', function () {
    messageInput.focus();
});

// 监听用户是否填完问卷数据
window.addEventListener("message", async function (event) {

    const msg = event.data;
    if (msg.type === "ghq-data") {
        const newData = {
            ...msg.data,
            id: question_id,  // 用上文取到的id号
            name: question_name,
            message: first_message // 用户的第一条消息，后面多轮对话需要更新
        };


        try {
            addMessage('问卷填写完成', 'user');
        } catch (err) {
            console.error("❌ 添加用户消息失败：", err);
        }

        messageInput.value = '';
        messageInput.style.height = 'auto';
        showTypingIndicator();

        try {
            const response = await fetch("/question1/", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: JSON.stringify(newData),
                credentials: 'include',
            });

            // 隐藏打字指示器，准备流式显示
            hideTypingIndicator();

            // 创建一个空的助手消息容器用于流式更新
            const assistantMessageDiv = createStreamingMessage();

            // 处理流式响应
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let assistantContent = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const jsonStr = line.substring(6);
                        if (jsonStr.trim()) {
                            try {
                                const data = JSON.parse(jsonStr);

                                // 处理流式内容
                                if (data.content) {
                                    assistantContent += data.content;
                                    updateStreamingMessage(assistantMessageDiv, assistantContent);
                                }
                            } catch (e) {
                                console.error('Error parsing JSON:', e);
                            }
                        }
                    }
                }
            }

            // 保存最终的助手回复到历史记录
            messageHistory.push({
                content: assistantContent,
                type: 'assistant',
                timestamp: new Date()
            });
            // 隐藏推荐问卷按钮和 iframe 问卷区域
            document.getElementById('questionnaireList').style.display = 'none';
            // document.getElementById('questionnaireEmbedArea').style.display = 'none';
            // hideTypingIndicator();
            // 添加下载分析报告按钮
            const downloadBtn = document.createElement('button');
            downloadBtn.textContent = '📄 下载分析报告';
            downloadBtn.style.marginTop = '20px';
            downloadBtn.style.padding = '10px 16px';
            downloadBtn.style.backgroundColor = '#4CAF50';
            downloadBtn.style.color = 'white';
            downloadBtn.style.border = 'none';
            downloadBtn.style.borderRadius = '5px';
            downloadBtn.style.cursor = 'pointer';

            // 假设你的分析报告为 Blob 或服务器生成的 URL
            downloadBtn.addEventListener('click', async () => {
                const response = await fetch("/download_report/", {
                    method: "GET",
                });
                if (!response.ok) {
                    throw new Error(`下载失败：${response.status}`);
                }
                // 把响应转成 Blob（二进制文件）
                const blob = await response.blob();

                // 生成一个临时 URL
                const url = window.URL.createObjectURL(blob);

                // 创建一个隐藏的 <a> 元素并触发点击
                const a = document.createElement('a');
                a.href = url;
                a.download = '分析报告.docx'; // 下载文件名
                document.body.appendChild(a);
                a.click();

                // 清理
                a.remove();
                window.URL.revokeObjectURL(url);
            });
            document.getElementById('questionnaireEmbedArea').appendChild(downloadBtn);
            hideTypingIndicator();


        } catch (error) {
            console.error("提交问卷失败：", error);
            addMessage("提交问卷失败，请稍后重试。", 'assistant');
        }
    }
});

// 显示用户信息
function showUserInfo(userData) {
    const userInfo = document.getElementById('userInfo');
    const authButtons = document.getElementById('authButtons');
    const userName = document.getElementById('userName');
    const userAvatar = document.getElementById('userAvatar');
    // 设置用户名
    userName.textContent = userData.user_info.username;
    // 设置头像（如果有图片则显示图片，否则显示用户名首字）
    if (userData.avatar) {
        userAvatar.innerHTML = `<img src="${userData.avatar}" alt="用户头像" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">`;
    } else {
        userAvatar.textContent = userData.user_info.username.charAt(0);
    }

    userInfo.style.display = 'block';
}

// 切换用户下拉菜单
function toggleUserDropdown() {
    const userDropdown = document.getElementById('userDropdown');
    userDropdown.classList.toggle('show');
}

// 查看个人资料
function viewProfile() {
    // 跳转到个人资料页面
    window.location.href = '/profile/';
}

// 查看设置
function viewSettings() {
    // 跳转到设置页面
    window.location.href = '/profile/';
}

// 复制消息内容
function copyMessage(button) {
    const messageContent = button.closest('.message-content').querySelector('.message-text');
    const text = messageContent.textContent || messageContent.innerText;

    console.log(navigator.clipboard && navigator.clipboard.writeText)

    // 检查 Clipboard API 是否可用
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
            handleCopySuccess(button);
        }).catch(err => {
            console.error('Clipboard API 复制失败:', err);
            fallbackCopy(text, button); // 尝试 fallback
        });
    } else {
        // 不支持 Clipboard API，使用 fallback 方法
        fallbackCopy(text, button);
    }
}

// fallback 方法：兼容旧浏览器
function fallbackCopy(text, button) {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            handleCopySuccess(button, true);
        } else {
            throw new Error('document.execCommand("copy") 失败');
        }
    } catch (err) {
        console.error("fallback 复制失败:", err);
        showErrorMessage("复制失败，请手动选择复制");
    } finally {
        document.body.removeChild(textarea);
    }
}

// 封装统一复制成功逻辑
function handleCopySuccess(button, isFallback = false) {
    const originalHTML = button.innerHTML;
    button.innerHTML = `
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <polyline points="20,6 9,17 4,12" stroke="currentColor" stroke-width="2" fill="none"/>
        </svg>
    `;
    button.style.color = '#10b981';


    button.style.transform = 'scale(0.95)';
    setTimeout(() => {
        button.style.transform = '';
    }, 150);

    setTimeout(() => {
        button.innerHTML = originalHTML;
        button.style.color = '';
    }, 1000);

    showSuccessMessage(isFallback ? '消息已复制（兼容模式）' : '消息已复制到剪贴板');
}


// 启用聊天输入
function enableChatInput() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');

    if (messageInput) {
        messageInput.disabled = false;
        messageInput.placeholder = '继续对话...';
        messageInput.focus();
    }

    if (sendButton) {
        sendButton.disabled = false;
    }
}

// 退出登录
function logout() {
    // 发送退出登录请求
    if (confirm('确定要退出登录吗？')) {
        // 这里应该发送AJAX请求到Django后端
        csrf_data = getCookie('csrftoken')
        fetch('/login/logout_api/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清除本地存储
                sessionStorage.removeItem('auth_token');
                sessionStorage.removeItem('user_info');
                localStorage.removeItem('refresh_token');

                // 刷新或跳转
                window.location.reload();
            } else {
                alert('退出登录失败，请重试');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('退出登录失败，请重试');
        });
    }
}

// 滚动到底部
function scrollToBottom() {
    const messagesArea = document.getElementById('messagesArea');
    if (messagesArea) {
        messagesArea.scrollTop = messagesArea.scrollHeight;
    }
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

document.addEventListener('DOMContentLoaded', function () {
    const user_info = sessionStorage.getItem('user_info');
    const token = sessionStorage.getItem('auth_token');
    const refresh_token = sessionStorage.getItem('refresh_token');
    userData = JSON.parse(user_info); // 解析用户信息JSON字符串
    // 把所有数据组装成对象，方便调用或传递
    const all_data = {
        user_info: userData,   // 这里是对象或 null
        token: token,      // 字符串或 null
        refresh_token: refresh_token  // 字符串或 null
    };
    if (all_data) {
        try {
            showUserInfo(all_data);
        } catch (e) {
            console.error('用户信息解析失败:', e);
        }
    } else {
        document.getElementById('userInfo').style.display = 'none';
        document.getElementById('authButtons').style.display = 'block';
    }
});

